<template>
  <section class="upload-info-section">
    <section class="common-text-block-section">
      <div class="title-section" v-if="isEdit !== null">
        <div class="title">
          数据信息
          <div class="title-btns">
            <template v-if="!editSwitchValue">
                <el-button
                  icon="el-icon-document-add"
                  type="primary"
                  v-if="!this.isEdit"
                  :disabled="!isShowCarryConfirm"
                  @click.native="onNotCarry"
                  size="small"
                  :loading="isBtnLoading"
                  >反结转</el-button
                >
                <el-button
                  icon="el-icon-document-add"
                  type="primary"
                  :disabled="!isShowCarryConfirm"
                  v-else
                  @click.native="onCarry"
                  size="small"
                  :loading="isBtnLoading"
                  >确认结转</el-button
                >
              <el-link :href="downloadCertificateUri"
                :underline="false" target="_blank"
                >
                <el-button icon="el-icon-download"
                  type="primary"
                  size="small">下载报表</el-button>
              </el-link>
              <el-popover
                ref="accountSubmitPopOver"
                placement="bottom"
                :visible-arrow="false"
                popper-class="accountSubmitPopOver"
                trigger="click"
                @hide="closeTaxAccrual"
                >
                 <div  class="backgroundContent" style="max-height:800px;">
                  <section class="inner-text-block-section">
                  <div class="title-section" style="margin-left:20;">
                    <div class="title">凭证预览</div>
                  </div>
                  <div class="form-section" id="certificate">
                  <!-- <div class="everypage" style="width:100%; margin-top:20px; min-height: 1028px;" v-for="(entry, key, i) in printableEntryList" :key="i"> -->
                    <div class="everypage" style="width:100%; margin-top:20px;" v-for="(entry, key, i) in printableEntryList" :key="i">
                    <center style="font-size: 20px;font-weight: 600;">记账凭证</center>
                    <center style="font-size:16px; font-weight:600;text-decoration:underline;">{{clientInfo.companyName}}</center>
                    <div><div style="float:left">记账时间： {{new Date().getFullYear()}}年{{new Date().getMonth() + 1}}月{{new Date().getDate()}}日</div> <div style="float:right;">分录编号: {{key}}</div></div>
                  <el-table
                    align="center"
                    :data="printableEntryList[key]"
                    :span-method="printableArraySpanMethod"
                    border
                    style="width: 100%">
                    <el-table-column
                      align="center"
                      label="会计科目">
                      <template slot-scope="scope">
                        {{ scope.row.borrowSubject ? scope.row.borrowSubject:scope.row.loanSubject }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      label="对手方">
                      <template slot-scope="scope">
                       {{ scope.row.borrowSide ? scope.row.borrowSide:scope.row.loanSide }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      label="借方金额">
                      <template slot-scope="scope">
                       {{ scope.row.borrowAmount ? scope.row.borrowAmount : "" }}
                      </template>
                    </el-table-column>
                    <el-table-column
                      align="center"
                      label="贷方金额">
                      <template slot-scope="scope">
                       {{ scope.row.loanAmount ?scope.row.loanAmount : "" }}
                      </template>
                    </el-table-column>
                  </el-table>
                  </div>
                  </div>
                  <div style="
                    display: flex;
	                  justify-content: space-between;
	                  align-items: center;
                    margin:5px;">
                    <el-button size="small" style="margin:0 auto;" type="primary" @click="handleWindowPrint('#certificate', clientInfo.companyName)">打印PDF</el-button>
                  </div>
                  </section>
                 </div>
                <el-button slot="reference" icon="el-icon-document" type="primary" size="small" >打印凭证
              </el-button>
              </el-popover>
               <el-popover
                ref="accountingEntrySheetPopOver"
                placement="bottom"
                popper-class="accountingEntrySheetPopOver"
                trigger="click"
                v-if="showInventoryAccountingEntry">
                <div class="popoverContent">
                  根据数据库内主营业务收入和库存商品的比例，生产成本率不能高于<span style="color:red;"> {{mainCostRatioTipValue}}%</span>, 否则库存商品期末值将为负数。<br/>
                  <div style="line-height:40px;"><span>请设置生产成本率: </span><el-input size="mini" id="costRatio" v-model="costRatio"> <template slot="append">%</template></el-input></div>
                  <br/>分录预览:
                  <el-table
                  :data="mainCostRatioEntry.itemList"
                  style="width:100%;"
                  border
                  :key="mainCostRatioEntryTableFlush"
                  :span-method="costRatioArraySpan">
                  <el-table-column label="业务日期">
                     <template>
                        {{mainCostRatioEntry.date}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="borrowSubject" label="借方科目"></el-table-column>
                  <el-table-column prop="borrowAmount" label="借方金额"></el-table-column>
                  <el-table-column prop="loanSubject" label="贷方科目"></el-table-column>
                  <el-table-column prop="loanAmount" label="贷方金额"></el-table-column>
                  <el-table-column prop="disc" label="备注">
                    <template>
                        {{mainCostRatioEntry.desc}}
                    </template>
                  </el-table-column>
                  </el-table>
                  <div style="
                    display: flex;
	                  justify-content: center;
	                  align-items: center;
                    margin-top:10px;">
                    <el-button size="small" style="margin:0 auto;" type="primary" @click="saveMainCostRatioEntry">确认生成</el-button>
                  </div>
                </div>
                  <el-button icon="el-icon-document"
                  size="small" style="margin-left:11px;" type="primary" slot="reference">
                  生成库存分录
              </el-button>
              </el-popover>
              <el-button v-if="showCostConfirm" size="small" type="primary" @click.native="switchCostExpensesDialogVisible">
                费用/成本项确认
              </el-button>
               <el-popover
                ref="accountSubmitPopOver"
                placement="bottom"
                :visible-arrow="false"
                popper-class="accountSubmitPopOver"
                trigger="click"
                @show="initTaxAccrual"
                @after-leave="closeTaxAccrual">
                <div class="backgroundContent">
                  <section class="inner-text-block-section">
                  <div class="title-section" style="magin-left:20">
                    <div class="title" >操作说明</div>
                  </div>
                  <div class="disc-section">
                  1.若使用代税宝进行一键报税后，该页面将显示代税宝已申报的各税种金额；<br>
                  2.若有部分税种是手动申报，则可点击【查询税务数据】获得其税务局数据，查询过程将持续30s，发起查询后可退出页面；<br>
                  3.若希望在申报前计提，则可手动录入数据生成分录；<br>
                  </div>
                  <div class="form-section">
                    <el-form label-position="right" label-width="150px" :inline="true" :model="TaxAccruals">
                    <el-form-item label="城建税">
                      <el-input v-model="TaxAccruals.urbanTax"></el-input>
                    </el-form-item>
                    <el-form-item label="教育附加税">
                      <el-input v-model="TaxAccruals.educateTotleTax"></el-input>
                    </el-form-item>
                    </el-form>
                    <el-form label-position="right" label-width="150px" :inline="true" :model="TaxAccruals">
                    <el-form-item label="企业所得税">
                      <el-input v-model="TaxAccruals.companyIncomeTax"></el-input>
                    </el-form-item>
                      <el-form-item label="个人经营所得税">
                      <el-input v-model="TaxAccruals.perManageTax"></el-input>
                    </el-form-item>
                    </el-form>
                    <el-form label-position="right" label-width="150px" :inline="true" :model="TaxAccruals">
                      <el-form-item label="个人所得税">
                      <el-input v-model="TaxAccruals.incomeTax"></el-input>
                    </el-form-item>
                      <el-form-item label="印花税">
                      <el-input v-model="TaxAccruals.stampTax"></el-input>
                    </el-form-item>
                  </el-form>
                  </div>
                  </section>
                  <div style="
                    display: flex;
	                  justify-content: space-between;
	                  align-items: center;
                    margin:5px;">
                    <el-button v-if="jitiQuering == 0" size="small" style="margin:0 auto;" type="primary" @click="operateTaxAccrual">查询税务数据</el-button>
                    <el-button v-if="jitiQuering == 1 || jitiQuering == 2" size="small" style="margin:0 auto;" type="info">查询中</el-button>
                    <el-button v-if="jitiQuering == 3" size="small" style="margin:0 auto;" type="success">查询完成</el-button>
                    <el-button size="small" style="margin:0 auto;" type="primary" @click="saveTaxAccrual">生成分录</el-button>
                  </div>
                </div>
                  <el-button icon="el-icon-document"
                  size="small" style="margin-left:11px;" type="primary" slot="reference">
                  税金计提
                </el-button>  
              </el-popover>
              <el-button icon="el-icon-back" @click.native="onBack"
                size="small"
                style="margin-left:11px;">返回
              </el-button>
            </template>
            <template v-else>
              <el-button
                icon="el-icon-document-add"
                type="primary"
                @click.native="addEntry"
                 size="small"
                >添加分录</el-button
              >
              <el-button icon="el-icon-refresh" :loading="isBtnLoading" size="small" @click.native="saveUpdate"
                >保存并更新报表</el-button
              >
            </template>
          </div>
        </div>
        <div class="title-actions">
          <div class="right" v-if="this.isEdit">
            <span class="edit-text">编辑分录</span>
            <el-switch v-model="editSwitchValue" :disabled="editSwitchValue"></el-switch>
          </div>
        </div>
      </div>
      <div class="data-table-content">
        <el-tabs tab-position="left">
          <el-tab-pane label="会计分录" name="0" lazy>
            <entryTable
              :data="entryList"
              :isEdit="editSwitchValue"
            ></entryTable>
          </el-tab-pane>
          <el-tab-pane label="利润表" name="1" lazy>
            <profitTable :data="profitList" />
          </el-tab-pane>
          <el-tab-pane label="资产负债表" name="2" lazy>
            <assetsLiabilities :data="balanceList" />
          </el-tab-pane>
          <!-- <el-tab-pane label="报税凭证" name="3"> -->
          <!-- <statementCashTable :data="assetsList" /> -->
          <!-- </el-tab-pane> -->
          <!-- <el-tab-pane label="挂账数据表" name="4" lazy>
            <accountDataTable :data="accountDataList" />
          </el-tab-pane> -->
          <el-tab-pane label="现金流量表" name="5" lazy>
            <cashFlowTable :data="cashFlowList" />
          </el-tab-pane>
          <el-tab-pane label="科目余额表" name="6" lazy>
            <subjectCashTable :data="subjectList" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </section>
    <div>
    <entryDialog
      :dialogVisible.sync="isAddEntryDialog"
      @onAddEntry="onAddEntry"
      :entryListLength="getEntryList"
    />
    </div>
    <cost-or-expenses-dialog :costExpensesDialogVisible="costExpensesDialogVisible" @costExpensesDialogVisibleChanged="switchCostExpensesDialogVisible"/>
  </section>
</template>

<script>
/**
 * @file 上传模块 / 客户信息纯展示模块
 */

import entryTable from "./entryTable";
import profitTable from "./profitTable";
import assetsLiabilities from "./assetsLiabilities";
import statementCashTable from "./statementCashTable";
import accountDataTable from "./accountDataTable";
import cashFlowTable from "./cashFlowTable";
import subjectCashTable from "./subjectCashTable";
import entryDialog from "./entryDialog";
import map from "@/components/map";
import utiles, { getPreMonth }  from '@/components/utiles.js';

import {
  createRowData,
  balanceDataToTable,
  entryListToTable,
} from "./dataHelper";
import costOrExpensesDialog from './costOrExpensesDialog.vue';

const CASH_FLOW_NAMES = {
  businessActInfo: "经营活动产生的现金流量",
  empPayroll: "支付的职工薪酬",
  manageAct: "经营活动产生的现金流量净额",
  materials: "购买原材料、商品、接受劳务支付的现金",
  payTax: "支付的税费",
  restAct: "支付其他与经营活动有关的现金",
  restManageAct: "收到其他与经营活动有关的现金",
  sellCommodity: "销售产成品、商品、提供劳务收到的现金",
  initialBalance: "初期现金余额",
  investActInfo: "投资活动产生的现金流量",
  assetBuy: "购建固定资产、无形资产和其他非流动资产支付的现金",
  assetInvest: "收回短期投资、长期债券投资和长期股权投资收到的现金",
  assetRecycle: "处置固定资产、无形资产和其他非流动资产收回的现金净额",
  investAct: "投资活动产生的现金流量净额",
  investIncome: "取得投资收益收到的现金",
  longTermIncome: "短期投资、长期债券投资和长期股权投资支付的现金",
  lastBalance: "后期现金余额",
  netIncrease: "现金净增加额度",
  raiseActInfo: "筹资活动产生的现金流量",
  allotProfit: "分配利润支付的现金",
  investorMoney: "吸收投资者投资收到的现金",
  raiseActProd: "筹资活动产生的现金流量净额",
  receiveMoney: "取得借款收到的现金",
  repayBorrowMoney: "偿还借款本金支付的现金",
  repayInterest: "偿还借款利息支付的现金",
};

export default {
  props: {
    companyName: {
      type: String,
    },
    clientInfo: {
      type: Object,
    },
  },
  data() {
    return {
      editSwitchValue: false,
      accountBillData: {},
      entryList: null,
      profitList: [],
      balanceList: [],
      accountDataList: [],
      isAddEntryDialog: false,
      cName: "",
      isEdit: null,
      cashFlowList: [],
      subjectList: [],
      isShowCarryConfirm: false,
      carryConfirm: false,
      isBtnLoading: false,
      costRatio:0, //生产成本率
      mainCostRatio:[], // 科目余额表-主营业务收入 用于生成库存分录
      initMainCostRatioBorrowAmount:0,
      mainCostRatioEntryTableFlush:false, //表格响应式更新关键字段
      mainCostRatioTipValue:0,
      showInventoryAccountingEntry:false,
      downloadCertificateUri:"",
      costExpensesDialogVisible: false,
      showCostConfirm:false,
      TaxAccruals:{
        companyAddedTax:0.0,
        companyIncomeTax:0.0,
        educateTax:0.0,
        incomeTax:0.0,
        stampTax:0.0,
        urbanTax:0.0,
        placeEducateTax:0.0,
        educateTotleTax:0.0,
        perManageTax:0.0,
      },
      jitipopoverVisible:false,
      jitiQuering: 0,
      jitiQueryTimer:undefined,
      printableEntryList:{},
      printableEntryListFormating:true,
    };
  },
  created() {
      this.init();
      this.downloadCertificateUri = this.downloadCertificate();
      this.initShowCostConfirm();
  },
  computed: {
    getEntryList() {
      const list = this.entryList || [];
      const item = list[list.length - 1] || {};
      return item.no ? item.no + 1 : 1
    }
  },
  methods: {
    onNotCarry() {
       this.isBtnLoading = true;
       this.$http('/smart/reverseConfirmAccountingEntity', {
         params: {
           cName: this.clientInfo.companyName,
         }
       }).then(() => {
         this.init();
         this.$message({
          message: "反结转成功",
        });
       }).finally(() => {
         this.isBtnLoading = false;
       })
    },
    onCarry() {
      this.isBtnLoading = true;
       this.$http('/smart/confirmAccountingEntity', {
         params: {
           cName: this.clientInfo.companyName,
         }
       }).then(() => {
         this.init();
         this.$message({
          message: "结转成功",
        });
       }).finally(() => {
         this.isBtnLoading = false;
       })
    },
    init() {
      this.$http
        .get("/smart/checkResultForWorkBench", {
          params: {
            cName: this.clientInfo.companyName,
          },
        })
        .then((res) => {
          let {
            accountingEntrySheet,
            incomeSheet,
            balanceSheet,
            transactionDataSheet,
            subjectBalanceSheet,
            cashFlowSheet,
            showConfirm,
            showInventoryAccountingEntry,
          } = res.data;

          accountingEntrySheet = accountingEntrySheet || {
            entryList: [],
          };

          incomeSheet = incomeSheet || {
            itemList: [],
          };
          balanceSheet = balanceSheet || {};
          transactionDataSheet = transactionDataSheet || {
            itemList: [],
          };
          let newData = {
            profitList: incomeSheet.itemList || [],
            accountDataList: [],
            cashFlowList: (cashFlowSheet || {}).itemList || []
          };

          this.isShowCarryConfirm = showConfirm;
          this.showInventoryAccountingEntry = showInventoryAccountingEntry;
          this.isEdit = typeof accountingEntrySheet.confirm === 'undefined'  ? null : !accountingEntrySheet.confirm;
          // 处理分录表数据
          newData.entryList = entryListToTable(accountingEntrySheet.entryList, this);

          // 处理挂账表数据
          transactionDataSheet.itemList.forEach((v, index) => {
            const { receiptItemList = [], paymentItemList = [] } = v;
            const list = [
              {
                // 需要合并的列index
                columnIndexs: [0, 1, 2, 3],
                // 对应需要合并的列需要合并几个，1表示显示不合并，
                colSpans: [1, 1, 1, 3],
                // 标题列
                headerTypes: [0, 2],
                ...createRowData(["编号", index + 1, "交易对手方", v.tradeSide]),
              },
              {
                columnIndexs: [0, 2, 4],
                colSpans: [2, 2, 2],
                headerTypes: [0, 2, 4],
                ...createRowData(["期初值", "", "本期发生额", "", "期末值"]),
              },
            ];

            if (index !== 0) {
              list.unshift({});
            }

            list.push({
              // columnIndexs: [0, 1, 3, 4],
              // colSpans: [1, 2, 1, 2],
              headerTypes: [0, 1, 2, 3, 4, 5],
              ...createRowData([
                "科目",
                "金额",
                "科目",
                "金额",
                "科目",
                "金额",
              ]),
            });

            ['yuYingFu', 'yuYingShou', 'otherYingShouFu'].forEach(n => {
              const item = v[n];
              if (item) {
                 list.push({
                  headerTypes: [0, 2, 4],
                  ...createRowData([
                    item.start &&  item.start.subjectName,
                    item.start &&  item.start.amount,
                    item.current &&  item.current.subjectName,
                    item.current &&  item.current.amount,
                    item.end &&  item.end.subjectName,
                    item.end &&  item.end.amount,
                  ]),
                });
              }
            })
            newData.accountDataList.push(...list);
          });

          // 资产负债数据处理
          if (balanceSheet) {
            newData.balanceList = balanceDataToTable(balanceSheet);
          }
          let rowsKey = 0;
          if(subjectBalanceSheet && subjectBalanceSheet.origin.itemList) {
            const subjectList = [
              {
                 // 需要合并的列index
                columnIndexs: [0, 1, 2, 4, 6],
                // 对应需要合并的列需要合并几个，1表示显示不合并，
                colSpans: [1, 1, 2, 2, 2],
                // 标题列
                headerTypes: [2, 4, 6],
                ...createRowData([
                   '',
                   '',
                   '期初值',
                   '',
                   '本期发生额',
                   '',
                   '期末值',
                   '',
                   1
                ])
              },
              {
                // 标题列
                headerTypes: [0, 1, 2, 3, 4, 5, 6, 7],
                ...createRowData([
                   '科目',
                   '对手方',
                   '借方金额',
                   '贷方金额',
                   '借方金额',
                   '贷方金额',
                   '借方金额',
                   '贷方金额',
                   2
                ])
              }
            ];
            
            let keys = Object.keys(subjectBalanceSheet.tree);
            let tree = subjectBalanceSheet.tree;
            console.log("科目余额表数据结构：", tree);
            keys.forEach(eleKey => {
              rowsKey = rowsKey + 1;
              subjectList.push(createRowData([
                   tree[eleKey].item.subject,
                   tree[eleKey].item.tradeSide,
                   tree[eleKey].item.periodStartValue && tree[eleKey].item.periodStartValue.borrowAmount,
                   tree[eleKey].item.periodStartValue && tree[eleKey].item.periodStartValue.loanAmount,
                   tree[eleKey].item.periodCurrentValue && tree[eleKey].item.periodCurrentValue.borrowAmount,
                   tree[eleKey].item.periodCurrentValue && tree[eleKey].item.periodCurrentValue.loanAmount,
                   tree[eleKey].item.periodEndValue && tree[eleKey].item.periodEndValue.borrowAmount,
                   tree[eleKey].item.periodEndValue && tree[eleKey].item.periodEndValue.loanAmount,
                   rowsKey * 1000
                ]));
            });
            console.log("subjectList：", subjectList);
            keys.forEach(eleKey => {
              rowsKey = rowsKey + 1;
              let parentIndex;
              if(tree[eleKey].hasChildren){
                parentIndex = subjectList.findIndex(subjectElement => {
                  return subjectElement.col0Title.indexOf(eleKey) > -1
                });
                
                if (subjectList[parentIndex].children == undefined) {
                   subjectList[parentIndex].children = []
                }
                  tree[eleKey].children.forEach((ele, Index) => {
                    subjectList[parentIndex].children.push(createRowData([
                      ele.subject,
                      ele.tradeSide,
                      ele.periodStartValue && ele.periodStartValue.borrowAmount,
                      ele.periodStartValue && ele.periodStartValue.loanAmount,
                      ele.periodCurrentValue && ele.periodCurrentValue.borrowAmount,
                      ele.periodCurrentValue && ele.periodCurrentValue.loanAmount,
                      ele.periodEndValue && ele.periodEndValue.borrowAmount,
                      ele.periodEndValue && ele.periodEndValue.loanAmount,
                      parentIndex * 1000 + Index + 1
                  ]))  
                  });
                  console.log("tree[eleKey]", tree[eleKey], subjectList[parentIndex].children);
              }
            });
            console.log("科目余额表数据结构：", subjectList);
          newData.subjectList = subjectList;
          }




          Object.assign(this, newData);
          this.detailInfo = res.data;
          let mainCostRatioIndex = subjectBalanceSheet.origin.itemList.findIndex((element) => {
            return element.code == "5001"; //寻找科目余额表内主营业务收入项
          });

          let stockGoodsIndex = subjectBalanceSheet.origin.itemList.findIndex((element) => {
            return element.code == "1405"; //寻找科目余额表内库存商品项
          });

          let maxAccountingEntrySheetNo = 0;
          accountingEntrySheet.entryList.forEach((element, index) => {
            if(element.no > maxAccountingEntrySheetNo){
              maxAccountingEntrySheetNo = element.no;
            }
          });
          if (mainCostRatioIndex != -1 && stockGoodsIndex != -1){
          this.mainCostRatioEntry = 
          {
            date:utiles.formateDate(),
            entryType: "INVENTORY",
            no: maxAccountingEntrySheetNo + 1,
            itemList:[{
              borrowSubject: "主营业务成本",
              itemType:"INVENTORY",
              loanNo: null,
              loanSide: "",
              loanSubjectCode: "",
              loanAmount: 0.0,
              borrowAmount: subjectBalanceSheet.origin.itemList[mainCostRatioIndex].periodCurrentValue.loanAmount,
              borrowSubjectCode:"5401",
              loanSubject:"",
              comment:"",
              borrowNo:"",
              borrowSide:""
            },
            {
              borrowSubject: "",
              itemType:"INVENTORY",
              loanNo: null,
              loanSide: "",
              loanSubjectCode: "1405",
              loanAmount: subjectBalanceSheet.origin.itemList[mainCostRatioIndex].periodCurrentValue.loanAmount,
              borrowAmount: 0,
              borrowSubjectCode:"",
              loanSubject:"库存商品",
              comment:"",
              borrowNo:"",
              borrowSide:""
            }
            ],
            desc:"库存结转"
          },
          this.initMainCostRatioBorrowAmount = subjectBalanceSheet.origin.itemList[mainCostRatioIndex].periodCurrentValue.loanAmount;
          this.mainCostRatioTipValue = subjectBalanceSheet.origin.itemList[stockGoodsIndex].periodEndValue.borrowAmount /
            subjectBalanceSheet.origin.itemList[mainCostRatioIndex].periodEndValue.loanAmount;
          this.mainCostRatioTipValue = Math.round(this.mainCostRatioTipValue*1000)/10;
          } else {
            this.showInventoryAccountingEntry = false;
          }
        });
    },
    tabClick(e) {
       if(e.name === '5') {
         if (this.cashFlowList.length) return;
          this.$http
            .get("/taxesStandard/getCashFlowTableMsg", {
              params: {
                cName: this.clientInfo.companyName,
                month: getPreMonth()
              },
            }).then(res => {
              const list = [];
              if(res.data) {
                Object.keys(res.data).forEach(v => {

                  if(!CASH_FLOW_NAMES[v]) return;
                   if(res.data[v] && typeof res.data[v] === 'object') {
                     list.push({
                       key: CASH_FLOW_NAMES[v]
                     })
                     Object.keys(res.data[v]).forEach(v2 => {
                       list.push({
                       key: CASH_FLOW_NAMES[v2],
                       value: res.data[v][v2]
                     })
                     })
                   } else {
                     list.push({
                       key: CASH_FLOW_NAMES[v],
                       value: res.data[v]
                     })
                   }
                })
              }
              this.cashFlowList = list;
            })
       }
    },
    addEntry() {
      this.isAddEntryDialog = !this.isAddEntryDialog;
    },
    onAddEntry(itemList) {
      this.entryList.push(...entryListToTable(itemList));
    },
    saveUpdate() {
      const { entryList } = this;
      const currentUser = utiles.getCurrentUser();
      let arrs = [];
      entryList.forEach((v) => {
        const item = arrs.find((i) => i.no === v.no);
        const { date, desc, no, rowSpan, isHigh, ...args } = v;

        if (args.borrowSubjectCode) {
          const borrowItem = map.subjectsList.find(
            (sub) => sub.code === args.borrowSubjectCode
          );
          if (borrowItem) {
            args.borrowSubject = borrowItem.text;
          }
        }
        if (args.loanSubjectCode) {
          const borrowItem = map.subjectsList.find(
            (sub) => sub.code === args.loanSubjectCode
          );
          if (borrowItem) {
            args.loanSubject = borrowItem.text;
          }
        }
        if (item) {
          item.itemList.push(args);
        } else {
          arrs.push({
            no,
            date,
            desc,
            itemList: [args],
          });
        }
      });
      this.isBtnLoading = true;
      this.$http({
        method: "post",
        url: "/smart/saveAccountingEntity",
        data: {
          isConfirm: false,
          count: arrs.length,
          entryList: arrs,
        },
        params: {
          bName: currentUser.bCompanyName,
          cName: this.clientInfo.companyName,
        },
      }).then((res) => {
        this.init();
        this.cashFlowList = [];
        this.$message({
          message: "保存成功",
        });
        this.editSwitchValue = !this.editSwitchValue;

      })
      .finally(() => {
        this.isBtnLoading = false
      })
    },
    onConfirm() {
       const currentUser = utiles.getCurrentUser();
      this.$confirm("确认无误后，将无法再次编辑了, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http({
          method: "post",
          params: {
            bName: currentUser.bCompanyName,
            cName: this.clientInfo.companyName,
          },
          url: "/smart/confirmAccountingEntity",
          data: {
            cName: this.clientInfo.companyName,
          },
        }).then((res) => {
          this.editSwitchValue = false;
          this.$message({
            type: "success",
            message: "确认成功!",
          });
          this.$router.back();
        });
      });
    },
    costRatioArraySpan({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0) {
          if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }else if(columnIndex === 5){
           if (rowIndex % 2 === 0) {
            return {
              rowspan: 2,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
    },
    saveMainCostRatioEntry(){
      const { entryList } = this;
      const currentUser = utiles.getCurrentUser();
      let arrs = [];
      entryList.forEach((v) => {
        const item = arrs.find((i) => i.no === v.no);
        const { date, desc, no, rowSpan, isHigh, ...args } = v;

        if (args.borrowSubjectCode) {
          const borrowItem = map.subjectsList.find(
            (sub) => sub.code === args.borrowSubjectCode
          );
          if (borrowItem) {
            args.borrowSubject = borrowItem.text;
          }
        }
        if (args.loanSubjectCode) {
          const borrowItem = map.subjectsList.find(
            (sub) => sub.code === args.loanSubjectCode
          );
          if (borrowItem) {
            args.loanSubject = borrowItem.text;
          }
        }
        if (item) {
          item.itemList.push(args);
        } else {
          arrs.push({
            no,
            date,
            desc,
            itemList: [args],
          });
        }
      });
      arrs.push(this.mainCostRatioEntry);
      console.log("即将上传参数：", entryList);
      this.$http({
        method: "post",
        url: "/smart/saveAccountingEntity",
        data: {
          isConfirm: false,
          count: arrs.length,
          entryList: arrs,
        },
        params: {
          bName: currentUser.bCompanyName,
          cName: this.clientInfo.companyName,
        },
      }).then((res) => {
        this.init();
        this.cashFlowList = [];
        this.$message({
          message: "保存成功",
        });
        this.editSwitchValue = !this.editSwitchValue;
      })
    },
  downloadCertificate(){
     const currentUser = utiles.getCurrentUser();
    return "/api/smart/downloadExcel?bName=" +
      currentUser.bCompanyName + "&cName=" + this.clientInfo.companyName;
  },

  onBack() {
    this.$router.back();
  },

  switchCostExpensesDialogVisible(costExpensesDialogVisible){
    if (!costExpensesDialogVisible){
      this.costExpensesDialogVisible = !this.costExpensesDialogVisible;
      console.log("this.costExpensesDialogVisible", this.costExpensesDialogVisible);
    } else {
      console.log("this.costExpensesDialogVisible", costExpensesDialogVisible);
      this.costExpensesDialogVisible = costExpensesDialogVisible;
    }
  },
  initShowCostConfirm(){
    this.$http.get("/smart/checkResultForWorkBench", {params: {
      cName:this.clientInfo.companyName,
      bName:this.clientInfo.bCompanyName,
    }}).then(res => {
      if (res.code == 0){
        this.showCostConfirm = res.data.showCostConfirm;
      } else {
        this.$message.error("费用成本项获取出错：", res.message);
      }
    })
  },
  initTaxAccrual(){
      this.getQueryStatus();
      this.$http.get("/taxesStandard/getTaxAccrual", {params: {
      cName:this.clientInfo.companyName,
      bName:this.clientInfo.bCompanyName,
      month:getPreMonth(),
    }}).then(res => {
      if (res.code == 0){
        this.TaxAccruals.companyAddedTax = res.data.companyAddedTax;
        this.TaxAccruals.companyIncomeTax = res.data.companyIncomeTax;
        this.TaxAccruals.educateTax = res.data.educateTax;
        this.TaxAccruals.incomeTax = res.data.incomeTax;
        this.TaxAccruals.stampTax = res.data.stampTax;
        this.TaxAccruals.urbanTax = res.data.urbanTax;
        this.TaxAccruals.placeEducateTax = res.data.placeEducateTax;
        this.TaxAccruals.educateTotleTax = res.data.educateTotleTax;
        this.TaxAccruals.perManageTax = res.data.perManageTax
      } else {
        this.$message.error("计提获取出错：", res.message);
      }
  })
  },
  closeTaxAccrual(){
    this.jitiQuering = 0;
  },
  saveTaxAccrual(){
    this.jitipopoverVisible = false;
    this.$http.post("/taxesStandard/updateTaxAccrual", {
      bname:this.clientInfo.bCompanyName,
      cname:this.clientInfo.companyName,
      month:getPreMonth(),
      ...this.TaxAccruals
    }).then(res => {
      if (res.code == 0) {
        this.$message.success("更新税金计提信息成功");
      } else {
        this.$forceUpdate();
        return this.$message.error("生成分录失败", res.message);

      }
    })
  },
  operateTaxAccrual(){
    this.$http.get("/taxesStandard/taxAccrualOperate", {
      params: {
        bName: this.clientInfo.bCompanyName,
        cName: this.clientInfo.companyName,
        month: getPreMonth()
      }
    }).then(res => {
      if (res.code == 0){
       this.jitiQuering = res.data; 
      }
    })
  },
  getQueryStatus(){
    this.$http.get("/taxesStandard/getTaxAccrualStatus", {
      params: {
        bName: this.clientInfo.bCompanyName,
        cName: this.clientInfo.companyName,
        month: getPreMonth(),
      }
    }).then(res => {
      if (res.code == 0) {
        this.jitiQuering = res.data;
      }
    })
  },
  xiazaipingzheng(){
    console.log("分录数据：", this.entryList);
  },
   formatEntryList(){
     let maps = {}; // 同一单号对手方数量的存储数据结构
     this.entryList.forEach((item, index, array) => {
       if (maps[item.no] != undefined){
        maps[item.no]+=1;
       } else {
        maps[item.no] = 0;
       }
       if (this.printableEntryList[item.no]) {
         this.printableEntryList[item.no][maps[item.no]] = item;
       } else {
         this.printableEntryList[item.no] = [item]
       }
     })
      Object.keys(this.printableEntryList).forEach((item, index, array) => {
        this.printableEntryList[item][maps[item] + 1] = {loanSubject: "备注", borrowSide: this.printableEntryList[item][0].desc};
      });
  },
  printableArraySpanMethod({ row, column, rowIndex, columnIndex }) {
        if (row.loanSubject == "备注") {
          if (columnIndex === 1) {
            return [1, 3];
          } else if (columnIndex === 1) {
            return [0, 0];
          }
        }
      },
  sleep(time){
    return new Promise((resolve) => setTimeout(resolve, time));
  },
  async handleWindowPrint(ele, companyName){
        console.log("666", document.head.innerHTML);
        let date = new Date();
        let month = date.getMonth() + 1;
        document.body.innerHTML =  document.querySelector( ele ).outerHTML;
        document.head.innerHTML = await document.head.innerHTML.replace(/<title>.*<\/title>/, ' <title>' + companyName + '_' + month + '</title>\n' +
        '<!--abcdefghijklmnopqrstuvwxyz-->'
        )
        while (document.head.innerHTML.indexOf('abcdefghijklmnopqrstuvwxyz') == -1 ){
          await sleep(10);
        }
        window.print();
        window.location.reload();
    },
  },
  watch:{
    costRatio:{
      handler(newValue, oldValue){
        this.mainCostRatioEntry.itemList[0].borrowAmount = Math.round(this.initMainCostRatioBorrowAmount * newValue) / 100; // 主营业务成本
        this.mainCostRatioEntry.itemList[1].loanAmount = this.mainCostRatioEntry.itemList[0].borrowAmount; // 库存商品
        this.mainCostRatioEntryTableFlush = !this.mainCostRatioEntryTableFlush;
      },
    },
    jitiQuering:{
      handler(newValue, oldValue){
        if (newValue == 1 || newValue == 2){
            this.jitiQueryTimer = setInterval(()=>{
            this.getQueryStatus();           
        }, 5000);
        } else {
          clearInterval(this.jitiQueryTimer);
        }
      }
    },
    entryList(){
      this.formatEntryList();
    }
  },
  components: {
    entryTable,
    profitTable,
    assetsLiabilities,
    statementCashTable,
    accountDataTable,
    entryDialog,
    cashFlowTable,
    subjectCashTable,
    costOrExpensesDialog
  },
};
</script>
<style lang="less" scoped>
@import "../../../assets/var.less";
.upload-info-section {
  display: flex;
  min-height: 600px;
  .common-text-block-section {
    flex: 1;
    margin-bottom: 0;
    .item {
      width: 49%;
    }
  }
  .common-text-block-section ~ .common-text-block-section {
    margin-left: 10px;
  }
  .iconfont::before {
    color: @color-grey-low;
  }
  .upload-info-section {
    display: flex;
    .left,
    .right {
      flex: 1;
    }
    .left span {
      font-size: 14px;
      &.bank {
        color: @color-error;
      }
      &.uploaded {
        color: @color-green;
      }
    }
  }
}
.text-section {
  flex: 1;
}
.title-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .title {
    flex: 1;
    display: flex;
    align-items: center;
  }
  .right {
    display: inline-flex;
    align-items: center;
  }
  .edit-text {
    margin-right: 5px;
  }
}
.title-btns {
  margin-left: 20px;
  display: inline-block;
  .el-button{
    margin-left:11px;
  }
  // .el-link{
  //   margin-left:11px;
  // }
}
.info-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.el-table__row td {
  min-height: 40px;
}
.area_popper{
  border: 1px solid rgb(0, 9, 22);
}

.popoverContent{
  .el-input {
    width:100px;
  }
  .el-input /deep/ #costRatio{
  width:60px;
  margin-right: 0;
}
}

.inner-text-block-section {
    .title-section,
    .inner-title-section {
        border-bottom: 1px solid #aaa;
        margin: 0 0 0 0;
        font-size: 16px;
        .title {
            border-left: 4px solid #1890ff;
            padding-left: 10px;
            margin: 10px 0;
        }
        .el-button--text {
            float: right;
            padding: 0;
        }
        .iconfont {
            margin-left: 7px;
        }
        .icon-edit {
            font-size: 12px;
        }
        .right {
            float: right;
            padding-right: 10px;
            font-size: 14px;
            color: @color-grey-low;
        }
    }
    .inner-title-section {
        margin: 0 0 20px 0;
    }

    .disc-section{
      font-size: 16;
      padding:10px;
      border-bottom: 1px solid #aaa;
    }

    .form-section{
      width:auto;
      max-height: 500px;
      margin-top: 10px;
      border-bottom: 1px solid #aaa;
      overflow: auto;
    }
    
    .text-section {
        > .item {
            display: inline-block;
            width: 206px;
            line-height: 2em;
        }
        > .single-line {
            display: block;
            width: auto;
        }
    }
}

#certificate /deep/ .el-table td th.is-leaf,.el-table--border, .el-table--group{
  border-color: black;
}

#certificate /deep/ .el-table--border::after, .el-table--group::after, .el-table::before{
  background-color:black;
}

#certificate /deep/ .el-table td, .el-table th.is-leaf,.el-table--border, .el-table--group{
    border-color: black;
    background-color: white;
    color: black;
  }

#certificate /deep/ .el-table__header tr th{
  border-color:black;
}

@media print {
  .everypage {page-break-after: always;}
  @page{
    margin: auto;
  }
}

</style>

<style lang="less">
  .accountSubmitPopOver{
    margin:0;
    padding:0;
    border: 1px solid #888;
    max-height: 600px;
    border-radius: 0;
    width:734px;
}
</style>